package com.nx.platform.es.bean.modle.score;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.nx.platform.es.common.utils.MoreMaps;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class DecayFunctionGeoPointParser implements ScoreFunctionFieldConfigParser {

    private static void validateGeoDistanceString(String name, String value) {
        Preconditions.checkState(value.length() > 0, "param " + name + " not found or empty");
        Preconditions.checkState(value.endsWith("m") || value.endsWith("km"),
                "param " + name + " found but format uncorrect");
        Preconditions.checkState(NumberUtils.isNumber(value.replaceAll("k?m", "")),
                "param " + name + " found but format uncorrect");
    }

    @Override
    public ImmutableMap<String, ?> parse(Map<?, ?> settings) {
        String fieldName = MoreMaps.getString(settings, "fieldName");
        Preconditions.checkState(!Strings.isNullOrEmpty(fieldName), "param fieldName not found");
        String scale = MoreMaps.getString(settings, "scale", "").trim();
        validateGeoDistanceString("scale", scale);
        String offset = MoreMaps.getString(settings, "offset", "").trim();
        validateGeoDistanceString("offset", offset);
        double decay = MoreMaps.getDoubleValue(settings, "decay", 0.5d);
        float weight = MoreMaps.getFloatValue(settings, "weight", 0f);
        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.put("fieldName", fieldName);
        builder.put("scale", scale);
        builder.put("offset", offset);
        builder.put("decay", decay);
        builder.put("weight", weight);
        return builder.build();
    }

}
